package com.sujinyang.stateless_service.shiro;

import com.sujinyang.stateless_service.common.Constans;
import com.sujinyang.stateless_service.common.Md5Utils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

public class StatelessRealm extends AuthorizingRealm {


    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof StatelessToken;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //根据具体的需求来确定此段代码
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        StatelessToken token = (StatelessToken)authenticationToken;
        String username = token.getUsername();
        String key = getKey(username);
        //服务端生成密文摘要
        String serverDigest = Md5Utils.digest(key,token.getParams());
        System.out.println(token.getClientDigest());
        System.out.println(serverDigest);
        //然后进行客户端消息摘要和服务器端消息摘要的匹配
        return new SimpleAuthenticationInfo(username, serverDigest, getName());
    }

    /**
     * 根据用户名获取相关的key值(这里统一对用户名使用同一个key值，生产环境下此处可以扩展根据用户名不同有不同的key值)
     * @param username
     * @return
     */
    private String getKey(String username) {
        return Constans.USERNAME_KEY;
    }
}
